<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="分类名称" style="width: 200px;" class="filter-item"
        @keyup.enter.native="handleFilter" />
        <!-- <el-select v-model="listQuery.lxtype" class="filter-item" placeholder="分类等级">
            <el-option v-for=" item  in  lxtypelist " :key="item.id" :label="item.name" :value="item.id" />
          </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
        @click="handleCreate">
        新建分类
      </el-button>
    </div>
    <!-- <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="上级分类" align="center">
        <template slot-scope="{row}">
          <span>{{ row.pname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面图片" align="center">
              <template slot-scope="{row}">
                <el-popover trigger="hover" placement="top">
                  <div><el-image style="width: 100px; height: 100px" :src="row.image"></el-image></div>
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">图片</el-tag>
                  </div>
                </el-popover>
              </template>
          </el-table-column>
      <el-table-column label="分类等级" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lxtype }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status == 1 ? '启用' : row.status == 2 ? '封禁' : row.status == 3 ? '暂停使用' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="首页显示" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.open | statusFilter">
            {{ row.open == 1 ? '显示' : row.open == 2 ? '不显示' : row.open == 3 ? '暂停使用' : '异常' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" /> -->
      <el-tree
      :data="list"
      node-key="id"
      default-expand-all
      :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.name }}</span>
        <span style="margin-left:10px"  v-if="data.lxtype==1 || data.lxtype==2">
          <el-button
            type="text"
            size="mini"
            @click="append(data)">
            新增
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="handleUpdate(data)">
            编辑
          </el-button>
          <el-button
            type="text"
            size="mini"   
            @click="handleDelete(data)">
            删除
          </el-button>
        </span>
        <span style="margin-left:10px"  v-if="data.lxtype==3">
          <el-button
            type="text"
            size="mini"   
            @click="handleDelete(data)">
            删除
          </el-button>
        </span>

      </span>
    </el-tree>


    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px"
        style="width: 500px; margin-left:50px;">
        <el-form-item label="图片">
              <el-upload
                  class="avatar-uploader"
                  action="https://cs4.hephp.cn/api/Banlist/update"
                  :show-file-list="false"
                  :on-success="handleonsuccess">
                  <img v-if="temp.image" :src="temp.image" class="avatar imgsa">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
          </el-form-item>
      
        <el-form-item label="类型" prop="lxtype">
          <el-radio-group v-model="temp.lxtype">
            <el-radio :label="1">顶级分类</el-radio>
            <el-radio :label="2">二级分类</el-radio>
            <el-radio :label="3">三级分类</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否首页显示" prop="lxtype">
          <el-radio-group v-model="temp.open">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="2">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        
  
        <el-form-item label="分类名称" prop="username">
          <el-input v-model="temp.name" />
        </el-form-item>
        
        <el-form-item label="上级分类" v-if="temp.lxtype==2">
          <el-select v-model="temp.pid" class="filter-item" placeholder="请选择">
            <el-option v-for=" item  in  list1 " :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="上级分类" v-if="temp.lxtype==3">
          <el-select v-model="temp.pid"  class="filter-item" placeholder="请选择">
            <el-option v-for=" item  in  list2 " :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
            <el-option v-for=" item  in  statusOptions " :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          {{textMap[dialogStatus]}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchPv, createArticle, updateArticle, getDel, getListAll } from '@/api/clist'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
//   import jsonData from './data.json';
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
const statusOptions = [
  { key: 1, display_name: '启用' },
  { key: 2, display_name: '封禁' },
]


export default {
  name: 'ComplexTable',
  components: { Pagination, UploadExcelComponent },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      // Area: jsonData,
      // cityQuery: [],
      // areaQuery: [],
      listall: [],
      province: "",
      city: '',
      area: "",
      listQuery: {
        page: 1,
        limit: 20,
        lxtype:'',
        name: ''
      },
      lxtypelist:[
        { id: '', name: '请选择' },
        { id: 1, name: '顶级分类' },
        { id: 2, name: '二级分类' },
        { id: 3, name: '三级分类' },
      ],
      importanceOptions: [1, 2, 3],
      statusOptions,
      imtype: false,
      showReviewer: false,
      temp: {
        id: undefined,
        name: '',
        lxtype: 1,
        status: 1,
        pid: '',
        image:'',
        open:1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改分类',
        create: '新增分类',
        impolephone: 'Impole'
      },
      list1: [],
      list2: [],
      rules: {},
      downloadLoading: false
    }
  },
 
  created() {
    this.getList()
    this.getListAlls()
    this.getListAlls2()
  },
  methods: {
    handleFilter(){
      
    },
    editinfo(data){

    },
    append(data) {
        // const newChild = { id: id++, label: 'testtest', children: [] };
        // if (!data.children) {
        //   this.$set(data, 'children', []);
        // }
        // this.list.children.push(newChild);
        this.resetTemp()
        console.log(data)
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.temp.lxtype = data.lxtype+1
        this.temp.pid = data.id
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })  
      },
      remove(node, data) {
        // const parent = node.parent;
        // const children = parent.data.children || parent.data;
        // const index = children.findIndex(d => d.id === data.id);
        // children.splice(index, 1);
      },
    handleRemove(file, fileList) {
          console.log(file);
          this.temp.image = ''
      },
    handlePreview(file) {
          console.log(file);
    },
    getListAlls(){
      getListAll({lxtype:1}).then(response => {
          this.list1 = response.data
      })
    },
    getListAlls2(){
      getListAll({lxtype:2}).then(response => {
          this.list2 = response.data
      })
    },
    handleonsuccess(response, file){
          console.log(file);
          this.temp.image = file.response.data
          console.log(this.temp);
    },

    listallimp() {
      let m = {
        ulist: this.listall
      }
      getImplist(m).then(response => {
        this.listall = []
        this.getList()
        this.impoleVisible = false
        this.imtype = false
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    
    
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        lxtype: 1,
        status: 1,
        pid: '',
        open:1,
        image:''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createArticle(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      let that = this
      this.$confirm('此操作将永久该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        that.Getdel(row.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    Getdel(id) {
      let mup = {
        id: id
      }
      getDel(mup).then(response => {
        if (response.code == 200) {
          this.$notify({
            title: 'Success',
            message: 'Update Successfully',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } else {
          this.$notify({
            title: 'Success',
            message: 'del none',
            type: 'error',
            duration: 2000
          })
        }

      })
    },

  }
}
</script>
<style lang="scss" scoped>
.imgsa{
  width:200px;
  height:200px;
}
</style>